package cn.kgm.server.interceptor;

import cn.kgm.core.context.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器：
 * 将请求头数据，封装到BaseContextHandler(ThreadLocal)
 * <p>
 * 该拦截器要优先于系统中其他的业务拦截器
 * <p>
 *
 * @author xck
 * @date 2022-07-05
 */
@Slf4j
public class HeaderThreadLocalInterceptor implements AsyncHandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

//        ContextUtil.setUserId(Convert.toLong(WebUtils.getHeader(request, ContextConstants.JWT_KEY_USER_ID)));
//        ContextUtil.setName(WebUtils.getHeader(request, ContextConstants.JWT_KEY_NAME));
//        ContextUtil.setMobile(WebUtils.getHeader(request, ContextConstants.JWT_KEY_MOBILE));
//        ContextUtil.setEmail(WebUtils.getHeader(request, ContextConstants.JWT_KEY_EMAIL));
//        ContextUtil.setUserUid(WebUtils.getHeader(request, ContextConstants.JWT_KEY_USER_UID));
//        ContextUtil.setTenantId(Convert.toLong(WebUtils.getHeader(request, ContextConstants.JWT_KEY_TENANT_ID)));
//        ContextUtil.setTenantCode(WebUtils.getHeader(request, ContextConstants.JWT_KEY_TENANT_CODE));
//        ContextUtil.setClientId(WebUtils.getHeader(request, ContextConstants.JWT_KEY_CLIENT_ID));
//
//        String traceId = request.getHeader(ContextConstants.TRACE_ID_HEADER);
//        MDC.put(ContextConstants.LOG_TRACE_ID, StrUtil.isEmpty(traceId) ? StrUtil.EMPTY : traceId);
//        MDC.put(ContextConstants.JWT_KEY_TENANT_ID, WebUtils.getHeader(request, ContextConstants.JWT_KEY_TENANT_ID));
//        MDC.put(ContextConstants.JWT_KEY_USER_ID, WebUtils.getHeader(request, ContextConstants.JWT_KEY_USER_ID));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ContextUtil.remove();
    }
}
